<template>
  <div id="picture-add-page">
    <h1>{{ route.query.id ? '修改图片' : '创建图片' }}</h1>
    <a-typography v-if="spaceId">
      <a-typography-text>保存到图片空间：</a-typography-text>
      <a-typography-link :href="`/space/my`">
        {{ spaceId }}
      </a-typography-link>
    </a-typography>

    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="file" tab="文件上传">
        <ImageUpload :on-success="onSuccess" :picture="picture" :space-id="spaceId" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL上传" force-render>
        <UrlUpload :on-success="onSuccess" :picture="picture" :space-id="spaceId" />
      </a-tab-pane>
    </a-tabs>

    <div v-if="picture.id" style="text-align: center">
      <a-space>
        <a-button @click="openEditModal" :icon="h(EditOutlined)">编辑图片</a-button>
        <a-button v-if="checkSize" @click="openAIPaintingModal" :icon="h(AimOutlined)"
          >AI扩图
        </a-button>
      </a-space>
    </div>

    <a-form
      v-if="picture.id"
      :model="formState"
      layout="vertical"
      name="normal_submit"
      class="login-form"
      @finish="submitForm"
    >
      <a-form-item
        name="name"
        label="名称"
        :rules="[{ required: true, message: '请输入图片名称!' }]"
      >
        <a-input v-model:value="formState.name" allow-clear placeholder="请输入图片名称">

        </a-input>
      </a-form-item>

      <a-form-item
        name="introduction"
        label="简介"
        :rules="[{ required: true, message: '请输入简介！' }]"
      >
       <a-space>
         <a-textarea
           v-model:value="formState.introduction"
           :autoSize="{ minRows: 2, maxRows: 5 }"
           placeholder="请输入简介"
           style="width: 60vw"
         />
         <a-tooltip>
          <template #title>AI 优化简介</template>
           <a-button :icon="h(RedditOutlined)" @click="aiRename"></a-button>
         </a-tooltip>
       </a-space>

      </a-form-item>


      <CategoryTagsForm v-model="formState" />

      <a-form-item>
        <a-button
          block
          :disabled="disable"
          type="primary"
          html-type="submit"
          class="login-form-button"
        >
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>

  <!--  编辑图片弹框-->
  <ImageEditModal
    ref="imageEditModalRef"
    :picture="picture"
    :space="space"
    :space-id="spaceId"
    :on-success="onSuccess"
  />
  <!--  AI 扩图-->
  <ImageAIPaintingModal
    ref="imageAIPaintingRef"
    :picture="picture"
    :space-id="spaceId"
    :on-success="onSuccess"
  />
</template>

<script setup lang="ts">
import { h } from 'vue'
import ImageUpload from '@/components/image/ImageUpload.vue'
import UrlUpload from '@/components/image/UrlUpload.vue'

import { computed, onMounted, reactive, ref } from 'vue'
import { editPictureUsingPost, getPictureVoByIdUsingGet } from '@/api/pictureController.ts'
import { useRoute, useRouter } from 'vue-router'
import CategoryTagsForm from '@/components/CategoryTagsForm.vue'
import ImageEditModal from '@/components/image/ImageEditModal.vue'
import {
  AimOutlined,
  EditOutlined,
  RedditCircleFilled,
  RedditOutlined,
} from '@ant-design/icons-vue'
import ImageAIPaintingModal from '@/components/image/ImageAIPaintingModal.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'

const picture = ref<API.Picture>({})

const route = useRoute()
const router = useRouter()

// 检测大小
const checkSize = computed(() => {
  return picture.value?.picWidth > 512 && picture.value?.picHeight > 512
})
// 上传方式
const activeKey = ref('file')
// 定义表单
const formState = reactive<API.PictureEditRequest>({
  // name: '美女',
  // introduction: '我是你的大粉丝，我喜欢你',
  // category: '海报',
  // tags: ['热门'],
})

const spaceId = computed(() => {
  return route.query.spaceId
})

const onSuccess = (pictureVO: API.PictureVO) => {
  picture.value = pictureVO
  formState.name = pictureVO.name
  formState.id = pictureVO.id
}
//
const submitForm = async (values) => {
  console.log(values)
  const res = await editPictureUsingPost({
    ...formState,
    spaceId: spaceId.value,
  })
  if (res.data.code != 0) {
    return
  }
  router.replace({
    path: spaceId.value ? `/space/${spaceId.value}` : '/',
  })
}

// 获取空间信息
const space = ref<API.SpaceVO>()
const getSpace = async () => {
  let id = route.query.spaceId
  if (!id) {
    return
  }
  const res = await getSpaceVoByIdUsingGet({
    id: id,
  })
  if (res.data.code === 0 && res.data.data) {
    space.value = res.data.data
  }
}

// ai重命名
let eventSource: EventSource | null = null

const aiRename = () => {
  // 创建 SSE 连接
  if (eventSource) {
    eventSource.close() // 如果已有连接，先关闭
  }

  const baseUrl = import.meta.env.VITE_APP_API_URL || ''
  const sseUrl = `${baseUrl}/api/ai/rename?prompt=${formState.introduction}`
  console.log('Connecting to SSE:', sseUrl)
  formState.introduction = ''

  eventSource = new EventSource(sseUrl)

  // 接收消息
  eventSource.onmessage = (event) => {
    console.log('Received SSE message:', event.data)
    const aiResponseText = event.data
    // 自动滚动到底部
    formState.introduction += aiResponseText
  }

  // 处理错误
  eventSource.onerror = (error) => {
    console.error('SSE connection error:', error)
    if (eventSource) {
      eventSource.close()
      eventSource = null
    }
  }
}

// 查询图片
const getPicture = async () => {
  const id = route.query.id
  if (!id) {
    return
  }
  const res = await getPictureVoByIdUsingGet({
    id: id,
  })
  if (res.data.code != 0) {
    return
  }
  picture.value = res.data.data
  formState.name = res.data.data.name
  formState.introduction = res.data.data.introduction
  formState.category = res.data.data.category
  formState.tags = res.data.data.tags
  formState.id = id
}

const disable = computed(() => {
  return !(formState.name && formState.introduction && formState.category)
})

// 编辑弹框
const imageEditModalRef = ref()
const openEditModal = () => {
  imageEditModalRef.value.openModal()
}

// ai 扩图
const imageAIPaintingRef = ref()
const openAIPaintingModal = () => {
  imageAIPaintingRef.value.openModal()
}

onMounted(() => {
  getPicture()
  getSpace()
})
</script>

<style scoped lang="scss">
#picture-add-page {
  width: 65%;
  margin: 0 auto;
}
</style>
